const WXAPI = require('../../utils/api')
const AUTH = require('../../utils/auth')

Page({
  data: {
    
  },
  onLoad(e) {
    // 读取分享链接中的邀请人编号
    if (e && e.inviter_id) {
      xhs.setStorageSync('referrer', e.inviter_id)
    }
    // 读取小程序码中的邀请人编号
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene)
      if (scene) {        
        xhs.setStorageSync('referrer', scene.substring(11))
      }
    }
    this.initBanners()
    this.getNotice()
    this.siteStatistics()
    this.about()
    this.fetchShops()
    this.usersDynamic()
    // 读取系统参数
    this.readConfigVal()
    getApp().configLoadOK = () => {
      this.readConfigVal()
    }
    // 启动定时器
    setTimeout(() => {
      this.updateUserInfoAndMobile()
    }, 3000)
  },
  readConfigVal() {
    const mallName = wx.getStorageSync('mallName')
    if (!mallName) {
      return
    }
    xhs.setNavigationBarTitle({
      title: mallName,
    })
    this.setData({
      comName: xhs.getStorageSync('comName'),
      website_0: xhs.getStorageSync('website_0'),
      website_1: xhs.getStorageSync('website_1'),
      kefu_url: xhs.getStorageSync('kefu_url'),
      kefu_corpId: xhs.getStorageSync('kefu_corpId'),
      url: xhs.getStorageSync('url'),
      qiyeweixin_open: xhs.getStorageSync('qiyeweixin_open'),
    })
  },
  async updateUserInfoAndMobile() {
    const userBaseInfo = getApp().globalData.userBaseInfo
    if (!userBaseInfo) {
      setTimeout(() => {
        this.updateUserInfoAndMobile()
      }, 1000)
      return
    }
    const code = await AUTH.wxaCode()
    if (!userBaseInfo.mobile) {
      this.setData({
        code,
        bindMobileShow: true
      })
      return
    }
  },
  bindMobileOk(e) {
    console.log(e.detail); // 这里是组件里data的数据
    this.setData({
      bindMobileShow: false
    })
  },
  bindMobileCancel() {
    this.setData({
      bindMobileShow: false
    })
  },
  async about() {
    const res = await WXAPI.cmsPage('about')
    if (res.code == 0) {
      this.setData({
        aboutData: res.data
      })
    }
  },
  async siteStatistics(){
    const res = await WXAPI.siteStatistics()
    if (res.code == 0) {
      this.setData({
        siteStatisticsData: res.data
      })
    }
  },
  async initBanners(){
    const res = await WXAPI.banners()
    if (res.code == 0) {
      this.setData({
        banners: res.data
      })
    }
  },
  async fetchShops() {
    const res = await WXAPI.fetchShops()
    if (res.code == 0) {
      this.setData({
        shops: res.data
      })
    }
  },
  onShareAppMessage(options) {
    // 用户点击右上角转发
    return {
      title: '"' + xhs.getStorageSync('comName') + '" ' + xhs.getStorageSync('share_profile'),
      path: '/pages/index/index',
      query: 'inviter_id='+ xhs.getStorageSync('uid')
    }
  },
  onShareTimeline(options) {
    // 用户点击右上角转发到朋友圈
    return {
      title: '"' + wx.getStorageSync('comName') + '" ' + wx.getStorageSync('share_profile'),
      path: '/pages/index/index',
      query: 'inviter_id='+ xhs.getStorageSync('uid')
    }
  },
  onShareChat(options) {
    // 用户点击右上角转发到微信群组
    return {
      title: '"' + wx.getStorageSync('comName') + '" ' + wx.getStorageSync('share_profile'),
      path: '/pages/index/index',
      query: 'inviter_id='+ xhs.getStorageSync('uid')
    }
  },
  async getNotice() {
    const res = await WXAPI.noticeLastOne()
    if (res.code == 0) {
      this.setData({
        noticeLastOne: res.data
      })
    }
  },
  goNotice() {
    xhs.navigateTo({
      url: '/pages/notice/show?id=' + this.data.noticeLastOne.id,
    })
  },
  copy(e) {
    const v = e.currentTarget.dataset.v
    xhs.setClipboardData({
      data: v,
    })
  },
  webview(e) {
    const v = e.currentTarget.dataset.v
    xhs.navigateTo({
      url: '/pages/webview/website?url=' + v,
    })
  },
  gomap(e) {
    const idx = e.currentTarget.dataset.idx
    const shop = this.data.shops[idx]
    xhs.openLocation({
      name: shop.name,
      address: shop.address,
      latitude: shop.latitude,
      longitude: shop.longitude,
      fail: err => {
        console.error(err);
      }
    })
  },
  callMobile(e) {
    const idx = e.currentTarget.dataset.idx
    const shop = this.data.shops[idx]
    xhs.makePhoneCall({
      phoneNumber: shop.linkPhone,
    })
  },
  async getPhoneNumber(e) {
    console.log(e);
    if (!e.detail.errMsg || e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        title: e.detail.errMsg,
        icon: 'none'
      })
      // this.updateUserInfoAndMobile()
      return;
    }
    let res
    const extConfigSync = wx.getExtConfigSync()
    if (extConfigSync.subDomain) {
      // 服务商模式
      res = await WXAPI.wxappServiceBindMobileV2({
        token: wx.getStorageSync('token'),
        code: e.detail.code
      })
    } else {
      res = await WXAPI.bindMobileWxappV2(wx.getStorageSync('token'), e.detail.code)
    }
    if (res.code == 0) {
      wx.showToast({
        title: '非常感谢～',
        icon: 'success'
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
    }
  },
  async usersDynamic() {
    const res = await WXAPI.usersDynamic(1)
    if (res.code == 0) {
      this.setData({
        usersDynamicList: res.data
      })
    }
  },
  kefu() {
    xhs.followOfficialAccount({
      fail: err => {
        console.error(err);
      },
      success: res => {
        if (res.status == 0) {
          // 关注成功
        } else {
          // 已经关注过了
        }
        console.log(res);
      }
    })
  },
});
